
<template>
  <section class="component add-queue">
    <el-card header>
      <el-form :model="model" :rules="rules" inline label-width="120px" ref="form">
        <el-form-item label="队列名称" prop="labelName">
          <el-input :disabled="openData===3" :max-length="50" placeholder="请输入队列名称" v-model.trim="model.labelName"></el-input>
        </el-form-item>
        <el-form-item label="队列状态" prop="labelStatus">
          <el-select clearable disabled placeholder="请选择" v-model="model.labelStatus">
            <el-option :key="code" :label="name" :value="code" v-for="{ code, name } in $dict.getDictData('LabelingStrategyStatus')"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <div class="row between-span" slot="header">
        <span>设置获取数据规则</span>
        <el-button @click="addNewConfigLine" v-if="openData===1||(openData===2&&modifyData.labelStatus==='READY')">增加</el-button>
      </div>
      <expression-base :flag="true" :modifyData="modifyData.labelStatus" :openData="openData" v-model="strategyDataSet"></expression-base>
    </el-card>
    <div class="operate-buttons">
      <el-button @click="emitClose">关闭</el-button>
      <el-button @click="submit" v-if="openData===1||(openData===2&&modifyData.labelStatus==='READY')">保存</el-button>
      <el-button @click="ObsoleteClick(1)" v-if="modifyData.labelStatus==='READY'">作废</el-button>
      <el-button @click="ObsoleteClick(2)" v-if="modifyData.labelStatus==='PUBLISHED'">终止</el-button>
    </div>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Prop, Emit, Model } from "vue-property-decorator";
import ExpressionBase from "~/components/system-manage/strategy-config/expression-base.vue";
import { IstrategyInfo } from "~/components/system-manage/strategy-config/strategy-helper.config";
import { Form } from "element-ui";
import { ValidatorService } from "~/utils/validator.service";
import { LabelingStrategyService } from "~/services/dataimp-service/labeling-strategy-service";

@Component({
  components: {
    ExpressionBase
  }
})
export default class AddQueue extends Vue {
  @Dependencies(LabelingStrategyService)
  private labelingStrategyService: LabelingStrategyService;

  @Prop({
    type: Object
  })
  private modifyData: object;
  @Prop({
    type: Number
  })
  private openData: number;
  private model: any = {
    labelName: "",
    labelStatus: "READY",
    formulaJson: "[]"
  };
  private rules = {
    labelName: { required: true, message: "请输入队列名称" },
    labelStatus: { required: true, message: "请选择队列状态" }
  };
  /**
   * 验证基础配置数据
   */
  public validate() {
    const form = this.$refs.form as Form;
    return Promise.all([
      form.validate(),
      this.validateExpression(),
      this.validateBreaketComplete()
    ]).then(() => this.emitBaseChange(this.model));
  }
  @Emit("add-queue")
  private emitBaseChange(v) {}
  @Emit("close")
  private emitClose() {
    this.strategyDataSet = [];
    this.model.id = "";
    this.refreshData();
  }
  @Emit("refreshData")
  private refreshData() {}

  // private priorityList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  private get strategyDataSet() {
    if (!this.model.formulaJson) return [];
    return JSON.parse(this.model.formulaJson) as IstrategyInfo[];
  }

  private set strategyDataSet(value) {
    this.model.formulaJson = JSON.stringify(value);
  }

  /**
   * 验证数据是否完整
   */
  private validateExpression() {
    const rules = {
      relation: { required: true, message: "请选择链接关系符" },
      variable: { required: true, message: "请选择字段" },
      symbol: { required: true, message: "请选择操作符" },
      value: { required: true, message: "缺少期望值" }
    };
    const results = this.strategyDataSet.map(v =>
      ValidatorService.validate(v, rules)
    );
    return Promise.all(results)
      .then(() => true)
      .catch(({ errors }) => {
        if (errors.length) this.$message(errors[0].message);
        return Promise.reject(false);
      });
  }

  /**
   * 验证连接符是否完整
   */
  private validateBreaketComplete() {
    if (!this.strategyDataSet.length) {
      this.$message("请配置数据规则");
      return Promise.reject("Error");
    }
    const result = this.strategyDataSet.reduce((s, c: IstrategyInfo) => {
      if (c.leftBracket === "(") s += 1;
      if (c.leftBracket === "((") s += 2;
      if (c.rightBracket === ")") s -= 1;
      if (c.rightBracket === "))") s -= 2;
      return s;
    }, 0);

    if (result === 0) {
      return Promise.resolve(true);
    } else {
      const message = result > 0 ? "缺少右括号 ）" : "缺少左括号（";
      this.$message(message);
      return Promise.reject("Error");
    }
  }

  private addNewConfigLine() {
    let addFlag = true;
    if (this.strategyDataSet.length) {
      const lastLine = this.strategyDataSet[this.strategyDataSet.length - 1];
      addFlag = !!lastLine.relation;
    }
    if (addFlag) {
      this.strategyDataSet.push({
        relation: "",
        variable: "",
        symbol: "",
        leftBracket: "",
        rightBracket: "",
        value: ""
      });
    } else {
      this.$message.warning("请完善数据规则");
    }
  }

  /**
   * 重置
   */
  private reset() {
    const form: any = this.$refs["form"];
    form.resetFields();
  }

  /**
   * 确定
   */
  private submit() {
    const validates = this.validate().catch(e => Promise.reject(e));
    validates.then(x => {
      this.labelingStrategyService
        .saveLabelingStrategy(this.model)
        .subscribe(data => {
          this.$message.success("操作成功！");
          this.emitClose();
          this.reset();
        });
    });
  }
  /**
   * 作废/终止
   */
  private ObsoleteClick(val) {
    const ObsoleteModel: any = {
      id: this.model.id,
      labelStatus: val === 1 ? "ABOLISHED" : "TERMINATED"
    };
    this.labelingStrategyService
      .updateLabelStatus(ObsoleteModel)
      .subscribe(data => {
        this.$message.success("操作成功！");
        this.emitClose();
        this.reset();
      });
  }

  private refresh(modifyData) {
    this.reset();
    if (modifyData.id) {
      this.model.labelName = modifyData.labelName;
      this.model.labelStatus = modifyData.labelStatus;
      this.model.formulaJson = modifyData.formulaJson;
      this.model.id = modifyData.id;
      console.log(modifyData.formulaJson,'queue215')
    }
  }
}
</script>

<style lang="less" scoped>
</style>
